package ute.mvc.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ute.mvc.model.User;

public class AuthenticationInterceptor implements HandlerInterceptor {
	private String redirect;

	public String createRedirectURL(HttpServletRequest request) {
		if (redirect.startsWith("/")) {
			return request.getContextPath() + redirect;
		} else {
			return redirect;
		}
	}

	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		// TODO Auto-generated method stub
		// Avoid a redirect loop for some urls
		if (!request.getRequestURI().endsWith("/home")
				&& !request.getRequestURI().endsWith("/logout")
				&& !request.getRequestURI().endsWith("/about")
				&& !request.getRequestURI().endsWith("/contact")
				&& !request.getRequestURI().endsWith("/news")
				&& !request.getRequestURI().endsWith("/reset")
				&& !request.getRequestURI().endsWith("/deny")
				&& !request.getRequestURI().endsWith(request.getContextPath())
				&& !request.getRequestURI().endsWith(
						request.getContextPath() + "/")) {
			User user = (User) request.getSession().getAttribute("user");
			if (user == null) {
				response.sendRedirect(request.getContextPath() + "/home");
				return false;
			} else {
				if (user.getRole() == 1) {
					// Admin
					if (request.getRequestURI().startsWith(
							request.getContextPath() + "/lecturer")
							|| request.getRequestURI().startsWith(
									request.getContextPath() + "/student")) {
						response.sendRedirect(request.getContextPath()
								+ "/deny");
						return false;
					}
				} else if (user.getRole() == 2) {
					// Lecturer
					if (request.getRequestURI().startsWith(
							request.getContextPath() + "/portal")
							|| request.getRequestURI().startsWith(
									request.getContextPath() + "/student")) {
						response.sendRedirect(request.getContextPath()
								+ "/deny");
						return false;
					}
				} else {
					// Student
					if (request.getRequestURI().startsWith(
							request.getContextPath() + "/lecturer")
							|| request.getRequestURI().startsWith(
									request.getContextPath() + "/portal")) {
						response.sendRedirect(request.getContextPath()
								+ "/deny");
						return false;
					}
				}
			}
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
